package com.boot.admin.modules.sys.ai.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.boot.admin.base.R;
import com.boot.admin.modules.sys.ai.model.entity.AiMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;

/**
 * 简单语音上传服务
 *
 * @author 李飞洋
 * @date 2025/9/24
 */
@Slf4j
@Service
public class SimpleAudioUploadService {

    @Autowired
    private AiMessageService aiMessageService;

    @Value("${server.port:8088}")
    private String serverPort;

    @Value("${qiniu.tts.audio.base-path:audio}")
    private String audioBasePath;

    /**
     * 上传用户语音并保存访问路径
     */
    public R<String> uploadAudio(String conversationId, MultipartFile audioFile) {
        try {
            // 基础验证
            if (audioFile == null || audioFile.isEmpty()) {
                return R.NG("语音文件为空");
            }

            // 生成唯一文件名
            String originalFilename = audioFile.getOriginalFilename();
            String extension = FileUtil.extName(originalFilename);
            String fileName = IdUtil.simpleUUID() + "." + extension;

            // 构建存储路径
            String relativePath = audioBasePath + "/" + conversationId + "/" + fileName;

            // 保存文件
            String audioUrl = saveAudioFile(audioFile, relativePath);

            String messageId = IdUtil.simpleUUID();

            // 更新消息表
            updateMessageWithAudio(messageId, audioUrl);

            log.info("语音上传成功 - 消息ID: {}, 音频URL: {}", messageId, audioUrl);
            return R.OK(audioUrl);

        } catch (Exception e) {
            log.error("语音上传失败", e);
            return R.NG("上传失败：" + e.getMessage());
        }
    }

    /**
     * 保存音频文件到存储目录
     */
    private String saveAudioFile(MultipartFile audioFile, String relativePath) throws Exception {
        // 获取资源目录路径
        String resourcePath = getResourcePath();
        Path fullPath = Paths.get(resourcePath, relativePath);

        // 创建目录
        Files.createDirectories(fullPath.getParent());

        // 写入文件
        Files.write(fullPath, audioFile.getBytes());

        // 返回访问URL
        return "http://localhost:" + serverPort + "/" + relativePath.replace("\\", "/");
    }

    /**
     * 更新消息表中的音频路径
     */
    private void updateMessageWithAudio(String messageId, String audioUrl) {
        AiMessage message = aiMessageService.getById(messageId);
        if (message != null) {
            message.setAudioUrl(audioUrl);
            message.setModified(LocalDateTime.now());
            aiMessageService.updateById(message);
        }
    }

    /**
     * 获取资源目录路径
     */
    private String getResourcePath() throws Exception {
        try {
            ClassPathResource resource = new ClassPathResource("");
            File resourceDir = resource.getFile().getParentFile();
            return new File(resourceDir, "classes").getAbsolutePath();
        } catch (Exception e) {
            String resourcePath = System.getProperty("user.dir") + "/src/main/resources";
            File resourceDir = new File(resourcePath);
            if (!resourceDir.exists()) {
                resourceDir = new File(System.getProperty("user.dir") + "/resources");
                resourceDir.mkdirs();
                resourcePath = resourceDir.getAbsolutePath();
            }
            return resourcePath;
        }
    }
}